package project.layer.agents;

import project.layer.ant.IntentionAnt;
import project.layer.physical.Crossroad;
import project.layer.physical.Road;
import project.layer.physical.Truck;
import project.layer.physical.commands.LeaveCrossroadCommand;

public class TruckAgentStateDeliveringPackage extends TruckAgentState {
	
	public TruckAgentStateDeliveringPackage(TruckAgent tAgent){
		super(tAgent);
	}
	@Override
	public void processTruckTick() {
		deliverPackage();

	}
	private void deliverPackage() {
		Truck truck = getTruckAgent().getTruck();
		boolean toBeExecuted = true;
		
		if(truck.isOnConnector() && truck.allCommandsProcessed()){
			

			Crossroad actualPosition = truck.getConnectorPosition().getConnector();
			if(actualPosition.hasDropOffPoint() && actualPosition.getDropOffPoint().getCorrespondingAgent().getId() == getTruckAgent().getIntention().getDestinations().getFirst() ){
				truck.deliverPackage();
				getTruckAgent().removeVisitedDestinationFromIntention(actualPosition.getDropOffPoint().getCorrespondingAgent().getId());
				if(getTruckAgent().getIntention().getDestinations().isEmpty()){
					getTruckAgent().removeTakenCrossroadFromIntention();
				}
				getTruckAgent().switchToPickUpState();
				toBeExecuted = false;
			}
			else{
				renewIntention();
				
			}
			
			if(toBeExecuted){
				Crossroad nextCrossroad = getTruckAgent().getIntention().getFollowingCrossroad(actualPosition);
				Road nextRoad = actualPosition.getConnectionTo(nextCrossroad);
				if(nextRoad != null){
					truck.addCommand(new LeaveCrossroadCommand(truck, nextRoad), getTruckAgent());
				}
				getTruckAgent().removeTakenCrossroadFromIntention();
				
				
			}
			

		}
		else {
			driveTillNextCrossroad();
		}		
		
	}
	
	

}
